/*
 * Copyright 2015 Yan Zhenjie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hiwan.unions.application.request;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import com.hiwan.unions.activity.loginRegister.LoginUserActivity;
import com.hiwan.unions.application.ConstantsValues;
import com.hiwan.unions.util.JsonUtil;
import com.hiwan.unions.util.ToastUtils;
import com.hiwan.unions.view.dialog.WaitDialog;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.error.NetworkError;
import com.yanzhenjie.nohttp.error.ServerError;
import com.yanzhenjie.nohttp.error.TimeoutError;
import com.yanzhenjie.nohttp.error.UnKnownHostError;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created in Nov 4, 2015 12:02:55 PM.
 *
 * @author Yan Zhenjie.
 */
public class HttpResponseListener<T> implements OnResponseListener<T> {

    private Activity mActivity;
    /**
     * Dialog.
     */
    private WaitDialog mWaitDialog;
    /**
     * Request.
     */
    private Request<?> mRequest;
    /**
     * 结果回调.
     */
    private HttpListener<T> callback;

    /**
     * @param activity     context用来实例化dialog.
     * @param request      请求对象.
     * @param httpCallback 回调对象.
     * @param isLoading    是否显示dialog.
     */
    public HttpResponseListener(Activity activity, Request<?> request, HttpListener<T> httpCallback, boolean isLoading) {
        this.mActivity = activity;
        this.mRequest = request;
        if (activity != null && isLoading) {
            mWaitDialog = new WaitDialog(activity);
            mWaitDialog.setCancelable(false);
        }
        this.callback = httpCallback;
    }

    /**
     * 开始请求, 这里显示一个dialog.
     */
    @Override
    public void onStart(int what) {
        if (mWaitDialog != null && !mActivity.isFinishing() && !mWaitDialog.isShowing()) {
            mWaitDialog.show();
        }
    }

    /**
     * 结束请求, 这里关闭dialog.
     */
    @Override
    public void onFinish(int what) {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
        }
    }

    /**
     * 成功回调.
     */
    @Override
    public void onSucceed(int what, Response<T> response) {
        if (callback != null) {
            String networkMillis = "";
            try {
                JSONObject myJsonObject = new JSONObject(response.get().toString());
                Logger.i("myJsonObject: " + myJsonObject.toString());
                int code = JsonUtil.getInt(myJsonObject, "code");
                if (code == 200) {
                    callback.onSucceed(what, response);
                } else {
                    networkMillis = myJsonObject.getString("msg");
                    SharedPreferences userInfo = mActivity.getSharedPreferences(ConstantsValues.INIT_USER_INFO,
                            Context.MODE_PRIVATE);
                    if (code == 500) {
                        ToastUtils.showToast(mActivity, networkMillis);
                    } else if (code == 800) {
                        ToastUtils.showToast(mActivity, networkMillis);
                        SharedPreferences.Editor editor = userInfo.edit();
                        editor.clear();
                        editor.putBoolean(ConstantsValues.IS_HASLOGIN, false);
                        editor.commit();
                        LoginUserActivity.startPreview2(mActivity);
                    }
                    callback.onFailed(what, code, networkMillis, false);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 失败回调.
     */
    @Override
    public void onFailed(int what, Response<T> response) {
        Logger.i("数据执行");
        String networkMillis = "";
        Exception exception = response.getException();
        if (exception instanceof NetworkError) {// 网络不好
            networkMillis = "网络异常，请稍后再试";
        } else if (exception instanceof ServerError) {// 服务器错误
            networkMillis = "网络连接超时，请稍后重试";
        } else if (exception instanceof TimeoutError) {// 请求超时
            networkMillis = "网络连接超时，请稍后重试";
        } else if (exception instanceof UnKnownHostError) {// 找不到服务器
            networkMillis = "网络连接超时，请稍后重试";
        } else if (exception instanceof UnKnownHostError) {// 找不到服务器
            networkMillis = "网络连接超时，请稍后重试";
        } else {
            networkMillis = "网络连接超时，请稍后重试";
        }
        ToastUtils.showToast(mActivity, networkMillis);
        Logger.e("错误：" + exception.getMessage());
        if (callback != null)
            callback.onFailed(what, 500, networkMillis, true);
    }

}
